<template>
  <div id="qcInstrSampleDiv">
    <Breadcrumb content="质控标本号对照" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="70">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">仪器</div>
              <vxe-select v-model="searchForm.instrId" :filterable="true" @change="valueChangeEvent">
                <vxe-option v-for="instr in instrList" :key="instr.id" :value="instr.id" :label="instr.instrName"></vxe-option>
              </vxe-select>

              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" @click="findInstrSampleAndItemDictList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="addInstrSample"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveInstrSampleList"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteInstrSample"></vxe-button>
            </template>
          </vxe-toolbar>

          <div class="tableBox">
            <vxe-table ref="instrSampleTableRef" @current-change="sampleRowClick" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="instrSampleList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>

              <vxe-column field="sampleNo" title="普通标本号" width="150" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.sampleNo" placeholder="" type="text"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="horizontal" title="对应质控水平" width="150" :edit-render="{}">
                <template #default="{ row }">
                  <span>{{ formatCommon(horizontalList, row.horizontal) }}</span>
                </template>
                <template #edit="{ row, rowIndex, column }">
                  <!-- 选择字典  -->
                  <vxe-select v-model="row.horizontal">
                    <vxe-option v-for="hobj in horizontalList" :key="hobj.id" :value="hobj.code" :label="hobj.name"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-column>

              <vxe-column field="batchNum" title="对应批号" width="150" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.batchNum" placeholder="" type="text"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="reqNo" title="固定条码号" width="150" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.reqNo" placeholder="" type="text" clearable></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="itemDictIds" title="包含的报告项目" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <span>{{ formatItemNameByIds(row) }}</span>
                </template>

                <!-- { field: '', title: '', type: 'checkbox', width: '30px' }, -->
                <template #edit="{ rowIndex }">
                  <SelectDataCheckedList :url="'/lis/lab/item/findLabItemDictListByInstr'" :column="[
                      { field: 'itemEnCode', title: '英文缩写' }, //列标题
                      { field: 'itemNa', title: '报告项目名称' },
                      { field: 'itemNo', title: '报告项目代码' }
                    ]" :searchParam="{ instrId: searchForm.instrId,poct:1 }" :isPage="false" @SelectCellClick="
                      (e) => {
                        selectRow(e, rowIndex);
                      }
                    " :clickRowId="sltInstrSample.itemDictIds" :showField="'itemNa'"></SelectDataCheckedList>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="30">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle rightTitile">当前仪器指控项目</div>
            </template>
          </vxe-toolbar>

          <div class="tableBox">
            <vxe-table ref="labItemDictTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="labItemDictList" :loading="dloading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source :checkbox-config="{
                checkMethod: checCheckboxkMethod2,
                checkRowKeys: defaultSelecteRowKeys
              }">
              <!--  -->
              <vxe-column type="checkbox" width="30px"></vxe-column>
              <vxe-column field="itemEnCode" title="英文缩写" width="100"> </vxe-column>
              <vxe-column field="itemNa" title="报告项目名称" width="100"> </vxe-column>
              <vxe-column field="itemNo" title="报告项目代码"> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';
import SelectDataGrid from '@/components/SelectDataGrid.vue';

let instrList: any = reactive([]); //左侧仪器下拉项
let instrSampleList: any = reactive([]); //左侧仪器表格数据
let labItemDictList: any = reactive([]); //右侧当前仪器指控项目表格数据
let rloading = ref(false);
let dloading = ref(false);
let horizontalList: any = reactive([]); //左侧对应质控水平选择字典
let sltInstrSample: any = {};
let defaultSelecteRowKeys = reactive([]);

let searchForm = reactive({
  instrId: ''
});

onMounted(() => {
  findInstrSetupList();
  getDictItemsList();
});

//批量获取字典(获取对应质控水平)
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['QCHORIZONTAL'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const horizontalType = dictTreeTypeItems.data.find((item) => item.code === 'QCHORIZONTAL');
  horizontalList.push(...horizontalType.detailDataList);
}

// 获取左侧仪器下拉选项数据(标题)
function findInstrSetupList() {
  instrList.length = 0; //放入数据前清空数据
  const url = '/lis/instrSetup/getInstrSetupList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '', poct: 1 }
    })
    .then((res: any) => {
      instrList.push(...res.data);
      if (instrList.length > 0) {
        searchForm.instrId = instrList[0].id;
        findInstrSampleAndItemDictList();
      }
    })
    .catch((err: any) => {
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}

// 获取左侧仪器表格数据+刷新+右侧表格数据
function findInstrSampleAndItemDictList() {
  rloading.value = true;
  dloading.value = true;
  instrSampleList.length = 0; //放入数据前清空数据
  labItemDictList.length = 0;
  const url = '/api/qc/qcInstrSample/findQcInstrSampleAndLabItemDictList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { instrId: searchForm.instrId, poct: 1 }
    })
    .then((res: any) => {
      instrSampleList.push(...res.data.sampleList);
      labItemDictList.push(...res.data.labItemDicts);
      if (instrSampleList.length > 0) {
        sampleRowClick({ row: instrSampleList[0] });
      } else {
        sltInstrSample = {};
      }
      rloading.value = false;
      dloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      dloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

// 仪器下拉选择 改变
function valueChangeEvent() {
  findInstrSampleAndItemDictList();
}

// 左侧新增
function addInstrSample() {
  if (isEmpty(searchForm.instrId)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    const record: any = {
      id: '',
      instrId: searchForm.instrId,
      sampleNo: '',
      batchNum: '',
      horizontal: '',
      reqNo: '',
      itemDictIds: '',
      qcItemIds: '',
      orgId: ''
    };
    instrSampleList.push(record);
  }
}
// 左侧保存
async function saveInstrSampleList() {
  if (isEmpty(searchForm.instrId)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.instrSampleTableRef;
    if ($Xtable) {
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = instrSampleList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateSamples = [] as any[];
      updateRecords.forEach((e: any) => {
        const iISample: any = {
          id: e.id,
          instrId: e.instrId,
          sampleNo: e.sampleNo,
          batchNum: e.batchNum,
          horizontal: e.horizontal,
          reqNo: e.reqNo,
          itemDictIds: e.itemDictIds,
          qcItemIds: e.qcItemIds,
          orgId: e.orgId
        };

        sveOrupdateSamples.push(iISample);
      });
      InsertRecords.forEach((e: any) => {
        const iISample: any = {
          id: e.id,
          instrId: e.instrId,
          sampleNo: e.sampleNo,
          batchNum: e.batchNum,
          horizontal: e.horizontal,
          reqNo: e.reqNo,
          itemDictIds: e.itemDictIds,
          qcItemIds: e.qcItemIds,
          orgId: e.orgId
        };
        sveOrupdateSamples.push(iISample);
      });

      if (sveOrupdateSamples.length > 0) {
        const url = '/api/qc/qcInstrSample/saveOrUpdateInstrSample';
        const obj: any = {};
        obj.qcInstrSampleList = sveOrupdateSamples;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('更新成功', VxeNotifyType.success);
            setTimeout(() => {
              findInstrSampleAndItemDictList();
            }, 500);
          })
          .catch((err: any) => {
            VxeMessage('更新失败', VxeNotifyType.success);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}
// 左侧删除
function deleteInstrSample() {
  const sltInstrSamples = (proxy.$refs.instrSampleTableRef as any).getCheckboxRecords();
  if (!(sltInstrSamples.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delInstrSampleList = sltInstrSamples.filter((p: any) => !isEmpty(p.id));
        if (delInstrSampleList.length > 0) {
          const data = { qcInstrSampleList: delInstrSampleList };
          const url = '/api/qc/qcInstrSample/batchDeleteInstrSampleList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findInstrSampleAndItemDictList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeInstrSampleList = sltInstrSamples.filter((p: any) => isEmpty(p.id));
        if (removeInstrSampleList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.instrSampleTableRef;
          if ($Xtable) {
            for (const removeRow of removeInstrSampleList) {
              await $Xtable.remove(removeRow);
              instrSampleList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}

function formatItemNameByIds(row) {
  if (!isEmpty(row.itemDictIds)) {
    const itemNames: any = [];
    const itemDictIdList = row.itemDictIds.split(',');
    for (const itemDictId of itemDictIdList) {
      const item = labItemDictList.find((item) => item.id === itemDictId);

      if (!isEmpty(item)) {
        itemNames.push(item.itemName);
      }
    }
    return itemNames.join(',');
  } else {
    return '';
  }
}

// 组件选中事件
function selectRow(row, index) {
  const nameArr = [];
  const idArr = [];
  row.forEach((item) => {
    nameArr.push(item.name);
    idArr.push(item.id);
  });
  const idString = idArr.join(',');
  instrSampleList[index].itemDictIds = idString;
}

// 左侧表格 点击当前行
function sampleRowClick({ row }) {
  if (isEmpty(row)) {
    sltInstrSample = {};
  } else {
    (proxy.$refs.instrSampleTableRef as any).setCurrentRow(row);
    sltInstrSample = row;
    rightTableChecked(); //获取右侧表格数据勾选状态
  }
}

// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  // 显示对钩状态 并且所有都禁止用户勾选
  return false;
  // console.log('sltInstrSample.itemDictIds',sltInstrSample.itemDictIds)
  // defaultSelecteRowKeys.length = 0;
  // const cekItemIdList = sltInstrSample.itemDictIds.split(',');
  // const obj = cekItemIdList.filter((p: any) => {
  //   defaultSelecteRowKeys.push(p);
  //   return p == row.id;
  // });
  // console.log('默认选中的框',defaultSelecteRowKeys)
  // return obj.length == 0;
}

// 设置行选中
const setSelectRow = (rows, checked) => {
  const $table = proxy.$refs.labItemDictTableRef;
  if ($table) {
    $table.setCheckboxRow(rows, checked);
  }
};

// 清除所有行选中
const clearSelectEvent = () => {
  const $table = proxy.$refs.labItemDictTableRef;
  if ($table) {
    $table.clearCheckboxRow();
  }
};

// 右侧表格数据勾选状态
function rightTableChecked() {
  // console.log('左侧表格当前行组件选择的id',sltInstrSample.itemDictIds)
  // console.log('右侧表格数据',labItemDictList)
  clearSelectEvent();
  defaultSelecteRowKeys.length = 0;
  if (!isEmpty(sltInstrSample.itemDictIds)) {
    const cekItemIdList = sltInstrSample.itemDictIds.split(',');
    labItemDictList.forEach((item: any) => {
      if (cekItemIdList.includes(item.id)) {
        setSelectRow(item, true);
        defaultSelecteRowKeys.push(item.id);
      }
    });
  }
}
</script>

<style lang="scss" scoped>
#qcInstrSampleDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
    }
    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
    // 右侧标题高度
    .rightTitile {
      height: 34px;
      line-height: 34px;
    }

    //右侧质控项目表格
    .tableBox {
      height: calc(100% - 40px);
    }
  }
}
</style>
